﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vit.Common.Models;

namespace Vit.Common
{
    public class PageOfList<T> : List<T>, IPageOfList<T>
    {
        public PageOfList(IQueryable<T> query, int pageIndex, int pageSize)
        {
            int totalItemCount = query.Count();
            if (pageIndex < 1)
                pageIndex = 1;

            if (pageIndex > 1 && totalItemCount <= pageSize)
                pageIndex = 1;

            query = query.AsQueryable().Skip((pageIndex - 1) * pageSize).Take(pageSize);

            AddRange(query.ToList());

            PagingInfo = new PagingInfo(pageIndex, pageSize, totalItemCount);
        }

        public PageOfList(IQueryable<T> query, int pageIndex, int pageSize, ICacheSupport cacheSupport)
        {
            int totalItemCount = query.Count();
            if (pageIndex < 1)
                pageIndex = 1;

            if (pageIndex > 1 && totalItemCount <= pageSize)
                pageIndex = 1;

            query = query.AsQueryable().Skip((pageIndex - 1) * pageSize).Take(pageSize);

            if (cacheSupport != null)
            {
                if (cacheSupport.ContainsData(query))
                {
                    AddRange(cacheSupport.GetCachedResult(query) as IEnumerable<T>);
                }
                else
                {
                    IEnumerable<T> data = query.ToList();
                    cacheSupport.CacheResult(query, data);
                    AddRange(data);
                }
            }
            else
            {
                AddRange(query.ToList());
            }

            PagingInfo = new PagingInfo(pageIndex, pageSize, totalItemCount);
        }

        #region IPageOfList<T> Members

        public PagingInfo PagingInfo { get; private set; }

        #endregion
    }
}
